<template>
  <div class="search_container">
    <div class="search">
      <van-icon name="arrow-left" @click="goBack" />
      <van-search
        v-model="value"
        shape="round"
        background="#c00000"
        placeholder="请输入搜索关键词"
        ref="search"
        @input="input"
        @clear="clear"
        clearable
      />
    </div>

    <!-- 历史搜索 -->
    <div class="history" v-if="searchResults.length === 0">
      <div class="hd">
        <span>搜索历史</span>
        <span><van-icon name="delete-o" @click="deleteHistory" /></span>
      </div>
      <div class="bd">
        <span
          v-for="(item, index) in historySearch"
          :key="index"
          @click="goToGoodsList(item)"
        >
          {{ item }}
        </span>
      </div>
    </div>

    <!-- 查询列表 -->
    <div class="searchList" v-else>
      <div
        class="searchItem_box"
        v-for="item in searchResults"
        :key="item.goods_id"
        @click="goToDetail(item)"
      >
        <div class="searchItem">{{ item.goods_name }}</div>
        <van-icon name="arrow" />
      </div>
    </div>
  </div>
</template>

<script>
import { Dialog } from 'vant';
export default {
  name: "Search",
  data() {
    return {
      // 延时器
      timer: null,
      // 输入的值
      value: "",
      // 搜索的关键值
      keyWord: "",
      // 搜索结果
      searchResults: [],
      // 历史搜索
      historySearch: [],
    };
  },
  methods: {
    firstCreate() {
      this.$store.commit("changeTabShow");
      if (localStorage.getItem("historySearch")) {
        this.historySearch = JSON.parse(localStorage.getItem("historySearch"));
      }
    },
    async getSearchList() {
      if (this.keyWord === "") {
        this.searchResults = [];
        return;
      }

      const { data: res } = await this.$http.get(
        `/api/public/v1/goods/qsearch?query=${this.keyWord}`
      );
      if (res.meta.status !== 200) return Toast.fail("数据请求失败");
      this.searchResults = res.message;

      // console.log(res);
    },
    deleteHistory() {
      Dialog.confirm({
        message: "确认清除历史记录吗？",
      })
        .then(() => {
          // on confirm
          this.historySearch = localStorage.setItem(
            "historySearch",
            JSON.stringify([])
          );
        })
        .catch(() => {
          // on cancel
          return
        });
    },

    clear() {
      this.historySearch.unshift(this.keyWord);
      localStorage.setItem("historySearch", JSON.stringify(this.historySearch));
      this.value = "";
    },

    input(val) {
      clearTimeout(this.timer);
      this.timer = setTimeout(() => {
        // 如果500毫秒，没有触发新的输入事件，则为搜索关键词赋值
        this.keyWord = val;
        // 根据关键词，查询搜索建议列表
        this.getSearchList();
      }, 500);
    },

    goToGoodsList(val) {
      this.$router.push({
        path: `/goodsList/${val}`,
        query: {
          query: val,
        },
      });
    },

    goToDetail(item) {
      this.$router.push(`/detail/${item.goods_id}`);
    },
    // 返回上一级目录
    goBack() {
      this.$router.go(-1);
    },
  },
  components: {},
  created() {
    this.firstCreate();
  },
  destroyed() {
    this.$store.commit("changeTabShow");
  },
};
</script>

<style lang="less" scoped>
.search_container {
  padding-top: 54px;
  .search {
    display: flex;
    justify-content: space-around;
    align-items: center;
    width: 100vw;
    position: fixed;
    left: 0;
    top: 0;
    z-index: 999;
    background-color: #c00000;
    /deep/ .van-icon-arrow-left {
      // box-sizing: content-box;
      background-color: #fff;
      flex: 10%;
      // color: #fff;
      padding: 6px;
      border-radius: 25px;
      margin-left: 5px;
      font-weight: bolder;
    }
    /deep/ .van-search {
      flex: 90%;
    }
  }
  .history {
    .hd {
      padding: 10px 5px;
      display: flex;
      justify-content: space-between;
      border-bottom: 1px solid #eaeaea;
      span {
        font-size: 12px;
      }
    }
    .bd {
      display: flex;
      flex-wrap: wrap;
      padding: 5px;
      span {
        padding: 3px 8px;
        margin: 3px 5px;
        border: 1px solid #e6e6e6;
        border-radius: 10px;
        color: #aaaaaa;
        font-size: 12px;
      }
    }
  }
  .searchList {
    // width: 100%;
    .searchItem_box {
      display: flex;
      justify-content: space-between;
      align-items: center;
      border-bottom: 1px solid #efefef;
      .searchItem {
        height: 40px;
        line-height: 40px;
        padding: 0 5px;
        font-size: 13px;
        white-space: nowrap;
        text-overflow: ellipsis;
        overflow: hidden;
      }
    }
  }
}
</style>